import React, { PureComponent } from 'react';
import {
  View,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  Image,
  ImageBackground,
  TouchableHighlight,
} from 'react-native';
import { connect } from 'react-redux';
import { Popup, Toast, UnitText, Wave, TopBar } from 'tuya-panel-kit';
import { AcrylicArrowCard, AcrylicItemCard } from 'tuya-panel-acrylic-kit';
import HomeTopView from './home-top-view';
import HomeLightView from './home-light-view';
import HomeFeedView from './home-feed-view';
import HomeTempView from './home-temp-view';
import HomeErrortipsView from './home-errortips-view';
import HomeMainView from './home-main-view';
import HomeTipView from './home-tip-view';
import HomeStatView from './home-stat-view';
import HomeBottomView from './home-bottom-view';
import { store } from '../../redux/configureStore';
import dpCodes from '../../config/dpCodes';
import TYSdk from '../../api';
import Strings from '../../i18n';
import { debounce } from '../../utils';
import Res from '../../res';
import strings from "../../i18n/strings";
import style from '../../config/style';
import kColor from "../../config/kColor";

const TYDevice = TYSdk.device;
const {
  fishtank_switch: fishtank_switchCode,
  fishtank_waterpump_switch: fishtank_waterpump_switchCode,
  fishtank_pump_flux: fishtank_pump_fluxCode,
  fishtank_water_pumpstatus: fishtank_water_pumpstatusCode,
  reset_filter_life: reset_filter_lifeCode,
  protect_status: protect_statusCode,
} = dpCodes;

class HomeScene extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      showToast: false,
      toastTips: '',
    };
    this.backgroundStyle="rgba(0,0,0,0)";
  }

  powerClicked = v => {
    console.log('鱼缸开关', v);
    TYDevice.putDeviceData({
      [fishtank_switchCode]: v,
    });
  };

  helpClicked = debounce(() => {
    console.log('使用帮助');
    TYSdk.Navigator.push({
      id: 'helpList',
      title: '',
    });
  });

  settingClicked = debounce(() => {
    console.log('设置');
    // TYSdk.Navigator.push({
    //   id: 'setting',
    // });
    this.props.navigation.navigate('setting');
  });

  filterClicked = debounce(() => {
    console.log('滤材');
    TYSdk.Navigator.push({
      id: 'filterList',
    });
  });

  pumpPopupClicked = debounce(v => {
    console.log('水泵档位', v);
    const {
      fishtank_waterpump_switch,
      fishtank_pump_flux,
      fishtank_water_pumpstatus,
      protect_status,
    } = this.props;
    if (
        fishtank_water_pumpstatus === 'disconnet' ||
        fishtank_water_pumpstatus === 'dump' ||
        fishtank_water_pumpstatus === 'fault'
    ) {
      return;
    }

    if (protect_status === 'Busy') {
      this.setState({ showToast: true, toastTips: Strings.feeder_protect_error });
      return;
    }

    let level;
    if (fishtank_waterpump_switch === false) {
      level = 'LEVEL0';
    } else {
      level = fishtank_pump_flux;
    }

    Popup.list({
      type: 'radio',
      titleTextStyle: { fontSize: 16, fontWeight: 'bold' },
      styles: { title: { fontSize: 16, fontWeight: 'bold' } },
      // cancelTextStyle: { width: 100, height: 40, borderRadius: 20, textAlign: 'center', backgroundColor: '#afd8ea' },
      confirmTextStyle: { fontSize: 16, fontWeight: 'bold', color: '#22a8dc' },
      iconTintColor: '#22a8dc',
      maxItemNum: 7,
      dataSource: [
        {
          key: '0',
          title: Strings.pump_switch_off,
          value: 'LEVEL0',
        },
        {
          key: '1',
          title: Strings.pump_level_1,
          value: 'LEVEL1',
        },
        {
          key: '2',
          title: Strings.pump_level_2,
          value: 'LEVEL2',
        },
        {
          key: '3',
          title: Strings.pump_level_3,
          value: 'LEVEL3',
        },
      ],
      title: Strings.pump_title,
      cancelText: Strings.cancel,
      confirmText: Strings.ok,
      value: level,
      onMaskPress: ({ close }) => close(),
      onSelect: (value, { close }) => {
        // setState({ listValue: value });
      },
      onConfirm: (value, { close }) => {
        if (value === 'LEVEL0') {
          TYDevice.putDeviceData({
            [fishtank_waterpump_switchCode]: false,
          });
        } else {
          if (fishtank_waterpump_switch === false) {
            TYDevice.putDeviceData({
              [fishtank_waterpump_switchCode]: true,
              [fishtank_pump_fluxCode]: value,
            });
          } else {
            TYDevice.putDeviceData({
              [fishtank_pump_fluxCode]: value,
            });
          }
        }
        close();
      },
    });
  });

  toastView(show, tips) {
    const { showToast, toastTips } = this.state;
    return (
        <Toast
            show={showToast}
            text={toastTips}
            onFinish={() => {
              this.setState({ showToast: false });
            }}
        />
    );
  }

  _onScroll = (event) => {
    const y = event.nativeEvent.contentOffset.y;
    const navigationHeight = TopBar.height*3;
    const opacityPercent = y / navigationHeight;


    this.backgroundStyle="rgba(0,0,0, "+opacityPercent+")";
    this._topViewItem.setNativeProps({
      style: { backgroundColor: this.backgroundStyle}
    });
  }

  topView() {
    return (
        <View
            ref={(c) => this._topViewItem = c}
            style={{ height: TopBar.height ,left:0,
              zIndex: 100,
              backgroundColor: '#00000000',
              top:0,right:0,width:TopBar.width,position:"absolute"}}>
        <TopBar.Container
            contentStyle={{ height: TopBar.height, marginTop: 10 }}
        >
          <TopBar.Action
              size={20}
              source={Res.fback}
              color="#ffffff"
              onPress={() => TYSdk.native.back()}
          />
          <TopBar.Content title={TYSdk.devInfo.name} color="#ffffff"/>
          <TopBar.Action name="pen" color="#ffffff" onPress={() => TYSdk.native.showDeviceMenu()} />
        </TopBar.Container>
        </View>
    );
  }

  render() {
    const { fishtank_switch, fishtank_waterpump_switch, fishtank_pump_flux, protect_status, fishtank_water_pumpstatus } = this.props;

    let pumplevelStr = '';
    if (fishtank_pump_flux === 'LEVEL1') {
      pumplevelStr = Strings.pump_level_1; //'1档';
    } else if (fishtank_pump_flux === 'LEVEL2') {
      pumplevelStr = Strings.pump_level_2; //'2档';
    } else if (fishtank_pump_flux === 'LEVEL3') {
      pumplevelStr = Strings.pump_level_3; //'3档';
    }
    if (fishtank_waterpump_switch === false) {
      pumplevelStr = Strings.pump_switch_off; //'关闭';
    }


    const isFeedProtecting = protect_status === 'Busy';
    // console.log('喂食保护是否生效：',protect_status);

    let isPumpEnable;
    isPumpEnable = !(!fishtank_switch || isFeedProtecting ||
        fishtank_water_pumpstatus === 'disconnet' || fishtank_water_pumpstatus === 'dump' || fishtank_water_pumpstatus === 'fault');


    return (
        <View style={styles.container}>
          {this.topView()}

          <ScrollView
              onScroll={this._onScroll}
              scrollEventThrottle={16}
              accessibilityLabel="HomeScene_ScrollView"
              contentContainerStyle={styles.scrollView}
          >
            {/* <NotificationLegacy
            style={{ flex: 1, height: 40 }}
            theme={{ background: '#5792C8' }}
            message="I am Notification"
          /> */}
            <ImageBackground
                source={fishtank_switch ? kColor.type === 'dark' ? Res.imageHomeBgOnDark : Res.imageHomeBgOnLight : null}
                resizeMode="stretch"
                style={styles.bgImg}
            >
              <HomeTopView />
            </ImageBackground>

            <HomeErrortipsView />

            {/* 电源开关 开机 关机 */}
            <View style={[styles.cellBg, kColor.theme[kColor.type].homeCardBgColor]}>
              <TouchableHighlight
                  style={[styles.cell]}
                  activeOpacity={0.5}
                  underlayColor="#DDDDDD"
                  onPress={() => {
                    this.powerClicked(!fishtank_switch);
                  }}
              >
                <View style={styles.iconAndText}>
                  <ImageBackground
                      style={fishtank_switch ? styles.powerOn : styles.powerOff}
                      source={Res.fpower}
                      resizeMode="center"
                  />
                  <Text style={[styles.cellText, kColor.theme[kColor.type].titleColor]}>
                    {fishtank_switch ? Strings.power_turn_off : Strings.power_turn_on}
                  </Text>
                </View>
              </TouchableHighlight>
            </View>

            {/* 灯光 */}
            <HomeLightView />

            {/* 喂食 */}
            <HomeFeedView />

            {/* 水泵 */}
            <View style={[styles.cellBg, kColor.theme[kColor.type].homeCardBgColor]}>
              <View style={[styles.cellMask, isPumpEnable ? style.grayHidden : style.grayBackground]}>
                <TouchableOpacity
                    disabled={!isPumpEnable}
                    style={[styles.cell]}
                    onPress={() => {
                      this.pumpPopupClicked();
                    }}
                >
                  <View style={styles.iconAndText}>
                    <ImageBackground style={styles.icon} source={Res.fpump} resizeMode="center" />
                    <Text style={[styles.cellText, kColor.theme[kColor.type].titleColor]}>{Strings.pump_title}</Text>
                  </View>
                  <View style={styles.iconAndText}>
                    <Text style={[ kColor.theme[kColor.type].rightTitleColor, { marginLeft: 20 }]}>{pumplevelStr}</Text>
                    <Image style={styles.arrow} source={Res.enter} />
                  </View>
                </TouchableOpacity>
              </View>
            </View>

            {/* 滤材 */}
            <View style={[styles.cellBg, kColor.theme[kColor.type].homeCardBgColor]}>
              <View
                  style={[styles.cellMask, !fishtank_switch ? style.grayBackground : style.grayHidden]}>
                <TouchableOpacity
                    disabled={!fishtank_switch}
                    style={styles.cell}
                    onPress={() => {
                      this.filterClicked();
                    }}
                >
                  <View style={styles.iconAndText}>
                    <ImageBackground style={styles.icon} source={Res.flvcai} resizeMode="center" />
                    <Text style={[styles.cellText, kColor.theme[kColor.type].titleColor]}>{Strings.filter_title}</Text>
                  </View>
                  <Image style={styles.arrow} source={Res.enter} />
                </TouchableOpacity>
              </View>
            </View>

            {/* 24小时温度 */}
            <HomeTempView />
            {/* 设置 */}
            <View style={[styles.cellBg, kColor.theme[kColor.type].homeCardBgColor]}>
              <TouchableOpacity
                  style={styles.cell}
                  onPress={() => {
                    this.settingClicked();
                  }}
              >
                <View style={styles.iconAndText}>
                  <ImageBackground style={styles.icon} source={Res.f1} resizeMode="center" />
                  <Text style={[styles.cellText, kColor.theme[kColor.type].titleColor]}>{Strings.page_title_setting}</Text>
                </View>
                <Image style={styles.arrow} source={Res.enter} />
              </TouchableOpacity>
            </View>
            <View style={{ height: 40 }} />
          </ScrollView>

          {this.toastView()}

          {/*{bottomDps !== undefined && <HomeBottomView dps={bottomDps} />}*/}
        </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    // backgroundColor: '#F7F7F7',
    backgroundColor: '#000',
  },
  bgImg: {
    width: '100%',
    height: 348,
  },
  card: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: '#fff',
    height: 80,
    width: '95%',
    marginHorizontal: 10,
    marginTop: 10,
    borderRadius: 12,
  },
  cellBg: {
    flex: 1,
    // alignItems: 'center',
    backgroundColor: '#fff',
    height: 80,
    marginHorizontal: 10,
    marginTop: 10,
    marginRight: 10,
    borderRadius: 12,
  },
  cellMask: {
    flex: 1,
    // alignItems: 'center',
    backgroundColor: '#fff',
    height: 80,
    marginTop: 0,
    marginRight: 0,
    borderRadius: 12,
  },
  cell: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: 'transparent',
    height: 80,
    marginHorizontal: 0,
    marginTop: 0,
    marginRight: 0,
    borderRadius: 12,
  },
  iconAndText: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  cellText: {
    marginStart: 13,
    fontSize: 16,
    fontWeight: 'bold',
    color: '#020202',
  },
  powerOn: {
    justifyContent: 'center',
    marginStart: 20,
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#f26f3f',
  },
  powerOff: {
    justifyContent: 'center',
    marginStart: 20,
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#211d3d',
  },
  icon: {
    justifyContent: 'center',
    marginStart: 20,
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#22a8dc',
  },
  arrow: {
    marginLeft: 5,
  },
  scrollView: {},
});

export default connect(({ dpState }) => ({
  dpState,
  fishtank_switch: dpState[fishtank_switchCode],
  fishtank_waterpump_switch: dpState[fishtank_waterpump_switchCode],
  fishtank_pump_flux: dpState[fishtank_pump_fluxCode],
  fishtank_water_pumpstatus: dpState[fishtank_water_pumpstatusCode],
  reset_filter_life: dpState[reset_filter_lifeCode],
  protect_status: dpState[protect_statusCode],
}))(HomeScene);
